<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
      xmlns:th="https://www.thymeleaf.org"
      xmlns:shiro="http://www.pollix.at/thymeleaf/shiro">
<head>
    <meta charset="utf-8">
    <title>layui</title>
    <meta name="renderer" content="webkit">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <link rel="stylesheet" href="/static/admin/lib/layui-v2.5.5/css/layui.css" media="all">
    <link rel="stylesheet" href="/static/admin/css/public.css" media="all">
    <style>
        .layui-table-cell{
            height:50px;
            line-height: 50px;
        }
        .ui-input-class{
            width: 60%;
        }
    </style>
</head>
<body>
<div class="layuimini-container">
    <div class="layuimini-main">

        <fieldset class="table-search-fieldset">
            <legend>搜索信息</legend>
            <div style="margin: 10px 10px 10px 10px">
                <form class="layui-form layui-form-pane" action="">
                    <div class="layui-form-item">
                        <div class="layui-inline">
                            <label class="layui-form-label">员工姓名</label>
                            <div class="layui-input-inline">
                                <input type="text" name="employeeName" autocomplete="off" class="layui-input">
                            </div>
                        </div>
                        <div class="layui-inline">
                            <label class="layui-form-label">员工性别</label>
                            <div class="layui-input-inline">
                                <input type="text" name="employeeSex" autocomplete="off" class="layui-input">
                            </div>
                        </div>
                        <div class="layui-inline">
                            <label class="layui-form-label">员工职位</label>
                            <div class="layui-input-inline">
                                <div class="layui-unselect layui-form-select downpanel cs">
                                    <div class="layui-select-title">
                                        <input type="text" placeholder="请选择品牌分类" value="" readonly="" class="layui-input layui-unselect"><i class="layui-edge"></i>
                                    </div>

                                    <dl class="layui-anim layui-anim-upbit" style="" id="RoleSelectCheckBox">

                                        <dd><input type="checkbox" name="roleId" title="IPoneX" value="1" lay-skin="primary" ></dd>

                                    </dl>
                                </div>
                            </div>
                        </div>
                        <div class="layui-inline">
                            <label class="layui-form-label">入司时间</label>
                            <div class="layui-input-inline">
                                <input type="text" id="queryEntryTime" name="entryTime" autocomplete="off" class="layui-input">
                            </div>
                        </div>
                        <div class="layui-inline">
                            <label class="layui-form-label">员工号</label>
                            <div class="layui-input-inline">
                                <input type="text" id="employeeNo" name="employeeNo" autocomplete="off" class="layui-input">
                            </div>
                        </div>
                        <div class="layui-inline">
                            <button type="submit" class="layui-btn layui-btn-primary"  lay-submit lay-filter="data-search-btn"><i class="layui-icon"></i> 搜 索</button>
                        </div>
                    </div>
                </form>
            </div>
        </fieldset>

        <script type="text/html" id="toolbarDemo">
            <div class="layui-btn-container">

                <button class="layui-btn layui-btn-normal layui-btn-sm data-add-btn" lay-event="add" shiro:hasPermission="employee:add"> 添加 </button>

                <button class="layui-btn layui-btn-sm layui-btn-warm data-delete-btn" lay-event="reloadEmp"> 刷新表格 </button>
                <button class="layui-btn layui-btn-sm layui-btn-primary data-update-btn" lay-event="updateRoleByEmp" shiro:hasPermission="employee:queryRole"> 查看角色 </button>
            </div>
        </script>

        <table class="layui-hide" id="emoloyeeTableId" lay-filter="currentTableFilter"></table>

        <div style="display: none;" id="currentTableBar">
            <a class="layui-btn layui-btn-normal layui-btn-xs data-count-edit" lay-event="edit" shiro:hasPermission="employee:recover">恢复</a>
            <a class="layui-btn layui-btn-xs layui-btn-danger data-count-delete" lay-event="delete" shiro:hasPermission="employee:ban">封禁</a>
        </div>

    </div>
</div>
<!-- 新增html  -->
<div class="layui-form layuimini-form" id="empAdd" style="display: none;">
    <div class="layui-form-item" style="margin-top: 20px;">
        <label class="layui-form-label required">用户名</label>
        <div class="layui-input-block">
            <input type="text" name="employeeName" lay-verify="required" lay-reqtext="员工姓名不能为空" placeholder="请输入员工姓名" value=""
                   class="layui-input ui-input-class">
            <tip>填写好员工的姓名</tip>
        </div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label required">性别</label>
        <div class="layui-input-block">
            <input type="radio" name="employeeSex" value="男" title="男" checked="">
            <input type="radio" name="employeeSex" value="女" title="女">
        </div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label required">联系手机号</label>
        <div class="layui-input-block">
            <input type="number" name="employeeTel" lay-verify="required" lay-reqtext="手机不能为空" placeholder="请输入手机" value=""
                   class="layui-input ui-input-class">
        </div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label required">员工身份证号</label>
        <div class="layui-input-block">
            <input type="text" name="idCard" lay-reqtext="员工身份证号不可为空" placeholder="请输入身份证号" value=""
                   class="layui-input ui-input-class">
        </div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label required">员工邮箱</label>
        <div class="layui-input-block">
            <input type="text" name="email" lay-verify="required" lay-reqtext="员工邮箱不可为空" placeholder="请输入员工邮箱" value=""
                   class="layui-input ui-input-class">
        </div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label required">入司时间</label>
        <div class="layui-input-block">
            <input id="entryTime" type="text" name="entryTime" lay-verify="required" lay-reqtext="入司时间不可为空" placeholder="点击选择日期" value=""
                   class="layui-input ui-input-class">
        </div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label required">选择职位</label>
        <div class="layui-input-block" id="roleCheckBox">

        </div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label required">选择部门</label>
        <div class="layui-input-block" style="width: 20%;">
            <select class="ui-input-class" name="departmentId" lay-verify="required">

            </select>
        </div>
    </div>

    <div class="layui-form-item">
        <label class="layui-form-label required">上传头像</label>
        <div class="layui-input-block">
            <input id="fileName" type="text" name="faceImage" lay-verify="fileName"
                   autocomplete="off" class="layui-input" disabled style="display: inline-block;width: 30%">

            <button type="button" class="layui-btn layui-btn-normal" id="uploadButton">
                <i class="layui-icon">&#xe67c;</i>上传图片
            </button>

            <!-- 显示图片区域 -->
            <div class="layui-collapse" style="width: 50%;">
                <div class="layui-colla-item" >
                    <h2 class="layui-colla-title">展开图片</h2>
                    <div class="layui-colla-content layui-show">
                        <div class="layui-colla-content" id="colla_img" style="">
                        </div>
                    </div>
                </div>
            </div>

        </div>

    </div>

    <div class="layui-form-item layui-form-text">
        <label class="layui-form-label">备注信息</label>
        <div class="layui-input-block">
            <textarea name="remark" class="layui-textarea ui-input-class" placeholder="请输入备注信息" ></textarea>
        </div>
    </div>

    <div class="layui-form-item">
        <div class="layui-input-block">
            <button class="layui-btn layui-btn-normal" lay-submit lay-filter="saveBtn">确认保存</button>
        </div>
    </div>
</div>

<!-- 更改用户角色弹窗 -->
<div id="updateRoleByEmp" style="display: none">
    <form class="layui-form" action="">
    <div class="layui-form-item">

        <label class="layui-form-label required">员工角色:</label>
        <div class="layui-input-block" id="updateRoleDiv">


        </div>
        <div class="layui-input-block">
            <span class="layui-bg-blue">勾选角色即可！</span>
        </div>
    </div>
    </form>
</div>
<script src="/static/admin/lib/layui-v2.5.5/layui.js" charset="utf-8"></script>
<script>
    layui.use(['form', 'table','laydate','upload','element','jquery'], function () {
        var $ = layui.jquery,
            form = layui.form,
            table = layui.table;
        var $ = layui.jquery;

        var laydate = layui.laydate;
        var upload = layui.upload;
        var element = layui.element;

        //执行一个laydate
        laydate.render({
            elem: '#entryTime' //指定元素
        });
        laydate.render({
            elem: '#queryEntryTime' //指定元素
        });

        //刷新下拉复选框
        $(".downpanel").on("click",".layui-select-title",function(e){
            var $select=$(this).parents(".layui-form-select");

            $(".layui-form-select").not($select).removeClass("layui-form-selected");
            $select.addClass("layui-form-selected");
            e.stopPropagation();
        }).on("click",".layui-form-checkbox",function(e){
            e.stopPropagation();
        });

        //刷新新增页面 角色 复选框
        $.ajax({
            url:'/admin/queryAllRole',
            type:'post',
            dataType:'json',
            success:function (res) {
                if (res.code == 200){

                    var selectCheckBoxHtml = "";

                    $.each(res.data, function(index, item) {

                        selectCheckBoxHtml += '<dd><input type="checkbox" name="roleIdList" title="'+item.roleName+'" value="'+item.roleId+'" lay-skin="primary" ></dd>';
                    });

                    $('#RoleSelectCheckBox').html(selectCheckBoxHtml);


                }
                form.render(); //重新渲染
            }
        })

        //执行实例
        var uploadInst = upload.render({
            elem: '#uploadButton' //绑定元素
            ,url: '/admin/uploadImages' //上传接口
            ,data:{
                imgPath:'face'
            }
            ,done: function(res){
                layer.msg('上传成功！~~~///(^v^)\\\~~~')
                //上传完毕回调
                $('#fileName').val(res.data); //展示文件名
                $('#colla_img').find('img').remove();
                $('#colla_img').css("display","block");
                $('#colla_img').append('<a href="#" onclick="openImg();"><img id="showImg" src="' + res.data + '" width="370px"></a>');

            }
            ,error: function(){
                //请求异常回调
                layer.msg('上传失败！' + index, {icon: 5});
            }
        });

        table.render({
            elem: '#emoloyeeTableId',
            url: '/admin/queryEmployeeRolePage',
            toolbar: '#toolbarDemo',
            defaultToolbar: [''],
            cols: [
                [
                {type: "checkbox"},
                {field:'employeeId',hide:true},
                {field: 'employeeNo', title: '员工号'},
                {title: '员工头像',templet:function (res) {

                        return '<img src="'+res.faceImage+'" width="45" height="45" style="border-radius:100%; "/>';
                    }},
                {field:'employeeName',title: '员工姓名'},
                {field:'employeeSex',title: '员工性别'},
                {field:'employeeTel',title: '员工手机'},
                {field:'idCard',title: '员工身份证'},
                {field:'email',title: '员工邮箱'},
                {field:'entryTime',title: '入司时间'},
                {title: '员工状态',templet:function (res) {
                        if (res.verify == 1){
                            return "正常";
                        }else{
                            return "封禁";
                        }
                    }},
                {field:'roleId',hide:true},
                {field:'roleName',title:'所在职位',templet:function (res) {
                                //根据员工id获取角色
                        return queryRoleByEmpId(res.employeeId);
                    }},
                {field:'remark',title:'员工备注'},
                {title: '操作', minWidth: 150, toolbar: '#currentTableBar', align: "center"}
                ]
            ],
            page: true,
            skin: 'line'
        });



        // 监听搜索操作
        form.on('submit(data-search-btn)', function (data) {
            var result = data.field;
            var id_array=[];
            $("input:checkbox[name='roleIdList']:checked").each(function() {
                id_array.push($(this).val());//向数组中添加元素
            });
            var idstr=id_array.join('-');//将数组元素连接起来以构建一个字符串

            //执行搜索重载
            table.reload('emoloyeeTableId', {
                where: {

                    employeeName:result.employeeName,
                    employeeSex:result.employeeSex,
                    entryTime:result.entryTime,
                    employeeNo:result.employeeNo,
                    roleIdList:idstr
                },
                url:'/admin/queryEmployeeByNameOrRole'

            });
            //一定要加，防止请求不通过
            return false;
        });

        //监听表单提交
        form.on('submit(saveBtn)', function(data){
            //将页面全部复选框选中的值拼接到一个数组中
            var arr_box = [];
            $("input[name='roleId']:checked").each(function() {
                arr_box.push($(this).val());
            });

            data.field.roleId = arr_box.join("-");

            $.ajax({
                url:'/admin/addEmployee',
                type:'post',
                data:data.field,
                dataType:'json',
                success:function (res) {

                    if (res.code == 200){
                        layer.confirm('新增成功，是否需要关闭弹窗?', {
                            btn : [ '确定', '取消' ]//按钮
                        }, function(index) {

                            layer.closeAll('page'); //关闭所有页面层
                            layer.close(index);

                        });
                        //刷新表格
                        table.reload('emoloyeeTableId', {
                            url: '/admin/queryEmployeeRolePage'

                        });
                    }

                }
            })

            return false; //阻止表单跳转。如果需要表单跳转，去掉这段即可。
        });

        //监听查看角色复选框
        form.on('checkbox(roleFilter)', function(data){

            var checked = data.elem.checked;
            var value = data.value;

            $.ajax({
                url:'/admin/addOrDeleteEmpRole',
                type:'post',
                data:{
                    type:checked,
                    roleId:value,
                    employeeId:data.elem.getAttribute("data-id")
                },
                dataType:'json',
                success:function(res){
                    layer.msg(res.message+",等待刷新~",function () {

                        table.reload('emoloyeeTableId', {
                            url: '/admin/queryEmployeeRolePage'

                        });

                    })
                }
            })



        });

        /**
         * toolbar监听事件
         */
        table.on('toolbar(currentTableFilter)', function (obj) {
            if (obj.event === 'add') {  // 监听添加操作
                var index = layer.open({
                    title: '添加用户',
                    type: 1,
                    area: ['70%', '80%'],
                    content: $('#empAdd'),
                    success:function (layero,index) {

                        //刷新新增页面 角色 复选框
                        $.ajax({
                            url:'/admin/queryAllRole',
                            type:'post',
                            dataType:'json',
                            success:function (res) {
                                $("select[name='departmentId']").html("");
                                if (res.code == 200){
                                    var html = "";
                                    var selectCheckBoxHtml = "";

                                    $.each(res.data, function(index, item) {

                                        html += '<input type="checkbox" name="roleId" value="'+item.roleId+'" title="'+item.roleName+'">';

                                        selectCheckBoxHtml += '<dd><input type="checkbox" name="roleId" title="'+item.roleName+'" value="'+item.roleId+'" lay-skin="primary" ></dd>';
                                    });

                                    $('#RoleSelectCheckBox').html(selectCheckBoxHtml);
                                    $('#roleCheckBox').html(html);


                                }
                                form.render(); //重新渲染
                            }
                        })

                        //新增页面部门下拉菜单
                        $.ajax({
                            url:'/admin/queryDepartmentPage',
                            type:'get',
                            dataType:'json',
                            success:function (res) {

                                $.each(res.data, function(index, item) {
                                    $("select[name='departmentId']").append(new Option(item.deptName,item.departmentId));
                                });

                                layui.form.render("select");
                            }
                        })



                    }
                });

            } else if (obj.event === 'updateRoleByEmp') {  // 监听更改用户角色操作
                var checkStatus = table.checkStatus('emoloyeeTableId')
                    , data = checkStatus.data;
                if (data.length == 0){
                    layer.msg("至少要选择一位用户")
                    return false;
                }else if(data.length >1){
                    layer.msg("只能选择一位用户")
                    return false;
                }else if(data.length == 1){

                    var emp = "span[name='empId"+data[0].employeeId+"']";
                    //声明角色id数组
                    var roleIds = [];
                    //获取所有的角色id
                    $(emp).each(function (index,item) {

                        roleIds.push($(this).attr("data-roleId"));

                    })
                    layer.open({
                        type: 1,
                        area:['500px','200px'],
                        content: $('#updateRoleByEmp'), //这里content是一个DOM，注意：最好该元素要存放在body最外层，否则可能被其它的相对元素所影响
                        success:function () {
                            //刷新出复选框
                            $.ajax({
                                url:'/admin/queryAllRole',
                                type:'post',
                                dataType:'json',
                                async:false,
                                success:function (res) {
                                    var html = '';

                                    $.each(res.data,function (index,item) {
                                        var count = 0;
                                        $.each(roleIds,function (index,it) {
                                            if (it == item.roleId){
                                                count++;
                                                return false;
                                            }
                                        })
                                        if (count >0){
                                            html += '<input type="checkbox" name="roleId" title="'+item.roleName+'" value="'+item.roleId+'" checked lay-filter="roleFilter" data-id="'+data[0].employeeId+'">';
                                        }else{
                                            html += '<input type="checkbox" name="roleId" title="'+item.roleName+'" value="'+item.roleId+'" lay-filter="roleFilter" data-id="'+data[0].employeeId+'">';
                                        }

                                    })

                                    $('#updateRoleDiv').html(html);

                                    form.render(); //更新全部
                                }
                            })
                        }
                    });

                    //layer.alert(JSON.stringify(data));

                }




            }else if(obj.event === 'reloadEmp'){  //监听刷新表格操作

                table.reload('emoloyeeTableId', {
                    url: '/admin/queryEmployeeRolePage'

                });

            }
        });

        //监听表格复选框选择
        table.on('checkbox(currentTableFilter)', function (obj) {

        });

        table.on('tool(currentTableFilter)', function (obj) {

            var data = obj.data;

            //恢复用户查看用户的状态是否为正常
            var verify = data.verify;

            if (obj.event === 'edit') {


                layer.confirm('是否要更改员工的状态？', function (index) {

                    if (verify == 1){
                        layer.msg("此员工正常无需恢复")
                    }else{
                        //修改用户的状态
                        $.ajax({
                            url:'/admin/updateEmployeeByEmpId',
                            type:'post',
                            data:{
                                employeeId:data.employeeId,
                                verify:1
                            },
                            dataType:'json',
                            success:function (res) {
                                layer.msg(res.message)
                                //刷新表格
                                table.reload('emoloyeeTableId', {
                                    url: '/admin/queryEmployeeRolePage'

                                });
                            }
                        })
                    }

                });

            } else if (obj.event === 'delete') {

                layer.confirm('是否要更改员工的状态？', function (index) {

                    if (verify == 0){
                        layer.msg("此员工已被封禁")
                    }else{
                        //修改用户的状态
                        $.ajax({
                            url:'/admin/updateEmployeeByEmpId',
                            type:'post',
                            data:{
                                employeeId:data.employeeId,
                                verify:0
                            },
                            dataType:'json',
                            success:function (res) {
                                layer.msg(res.message)

                                //刷新表格
                                table.reload('emoloyeeTableId', {
                                    url: '/admin/queryEmployeeRolePage'

                                });

                            }
                        })
                    }

                });
            }
        });


        //根据员工id获取角色
        function queryRoleByEmpId(employeeId){
            var html = '';
            $.ajax({
                url:'/admin/queryRoleByEmpId/'+employeeId,
                type:'get',
                dataType:'json',
                async:false,
                success:function (res) {

                    $.each(res.data,function (index,item) {
                        html += '<span name="empId'+employeeId+'" class="layui-badge layui-bg-blue" data-roleId="'+item.roleId+'">'+item.roleName+'</span> | ';
                    })

                }
            })
            return html;
        }

    });

    /*查看大图*/
    function openImg() {
        var idBar = '#showImg';
        var src = $(idBar)[0].src;
        var width = $(idBar).width();
        var height = $(idBar).height();
        var scaleWH = width / height;
        var bigH = 550;
        var bigW = scaleWH * bigH;
        if (bigW > 1000) {
            bigW = 1000;
            bigH = bigW / scaleWH;
        } // 放大预览图片
        parent.layer.open({
            type: 1,
            title: false,
            closeBtn: 1,
            shadeClose: true,
            area: [bigW + 'px', bigH + 'px'], //宽高
            content: '<img width="' + bigW + '" src="' + src + '" />'
        });
    }
</script>


</body>
</html>
